package com.streamax.app.cqbus.platform.ext

import android.util.Base64
import com.kt.coroutinedemo.utils.PacketUtils

import java.lang.reflect.Type
import java.nio.charset.Charset



val String.hexToByteArray: ByteArray
    get() = run {
        // 移除空格并转换为大写
        val hex = this.replace(" ", "").uppercase()

        // 检查长度是否为偶数
        if (hex.length % 2 != 0) {
            throw IllegalArgumentException("十六进制字符串长度必须为偶数")
        }

        return hex.chunked(2) // 每两个字符分为一组
            .map { it.toInt(16).toByte() } // 转换为字节
            .toByteArray()
    }


val String.toByteArrayGB2312End0: ByteArray
    get() = run {
        if (this.length <= 0) {
            (0).toByteArray
        } else {
            val charset = Charset.forName("GB2312")
            val strByteArray = this.toByteArray(charset)
            val end0 = (0).toByteArray
            PacketUtils.bytesMerger(mutableListOf(strByteArray, end0))
        }
    }



/**
 * 将Base64字符串转换回ByteArray
 */
var String.toBase64ByteArray : ByteArray
    get() = run {
        Base64.decode(this, Base64.DEFAULT)
    }
    set(value) {}

/**
 * 将Ip转成4的bytearray
 */
var String.ip2ByteArray : ByteArray
    get() = run {
        var buffer = ByteArray(4)
        var ips : List<Int> = this.split(".").map { it.toInt() }
        if (ips.size != 4)
        {
            return byteArrayOf(0)
        }
        buffer[0] = (ips[0] and 0xFF).toByte()
        buffer[1] = (ips[1] and 0xFF).toByte()
        buffer[2] = (ips[2] and 0xFF).toByte()
        buffer[3] = (ips[3] and 0xFF).toByte()

        return buffer
    }
    set(value){}
